package fzu.functiongather.MultipleChoice;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lidong.photopicker.PhotoPickerActivity;
import com.lidong.photopicker.PhotoPreviewActivity;
import com.lidong.photopicker.SelectModel;
import com.lidong.photopicker.intent.PhotoPickerIntent;
import com.lidong.photopicker.intent.PhotoPreviewIntent;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import fzu.functiongather.BaseActivity;

import fzu.functiongather.R;
import fzu.functiongather.Utils.ToastUtils;
import fzu.functiongather.mUtils.ImageFactory;
import fzu.functiongather.mUtils.MyGridView;
import fzu.functiongather.mUtils.NetUtils;


/**
 * Created by Administrator on 2016/12/9.
 */
public class MultipleChoiceActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener{

    //回调函数请求参数
    private static final int FINISH_SELF = 3;
    private static final int REQUEST_CAMERA_CODE = 10;
    private static final int REQUEST_PREVIEW_CODE = 20;
    private static final int MY_PERMISSIONS_REQUEST_STORAGE_CODE = 17;

    //图片选择
    private MyGridView gv_select_house_picture;
    private ArrayList<String> imagePaths = new ArrayList<>();
    private GridAdapter gridAdapter;
    private String imgs = "000000";
    private int clickPosition = 0;
    private ArrayList<String> listExtra = new ArrayList<>();
    private HashMap<String, File> selectImageFileMap = new HashMap<>();
    private File newFile = null;
    private List<String> compressImageList = new ArrayList<>();
    private int totalImageNum = 0;
    private List<String> pathList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.multiple_choice);
        initView();
    }


    private void initView() {
        //图片选择
        gv_select_house_picture = (MyGridView) findViewById(R.id.gv_select_house_picture);
        gv_select_house_picture.setOnItemClickListener(this);
        imagePaths.add("000000");
        gridAdapter = new GridAdapter(imagePaths);
        gv_select_house_picture.setAdapter(gridAdapter);
    }
    /**
     * 调用图片选择器----------------------------------------------------
     */


    /**
     * 读取内存权限请求
     */
    public void requestReadStorageRuntimePermission() {
        if (ContextCompat.checkSelfPermission(MultipleChoiceActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MultipleChoiceActivity.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_STORAGE_CODE);
        } else {
            LoadFolderAndImages();
        }
    }

    /**
     * 权限请求回调函数
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_STORAGE_CODE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    LoadFolderAndImages();
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(MultipleChoiceActivity.this, "权限错误，无法正常工作！", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }

    /**
     * 若点击的图片是添加图片按钮，则打开图片库
     * 若点击的是已添加的图片，则打开预览
     */
    private void LoadFolderAndImages() {
        if ("000000".equals(imgs)) {
            PhotoPickerIntent intent = new PhotoPickerIntent(MultipleChoiceActivity.this);
            intent.setSelectModel(SelectModel.MULTI);
            intent.setShowCarema(true); // 是否显示拍照
            intent.setMaxTotal(4); // 最多选择照片数量，默认为6
            intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
            startActivityForResult(intent, REQUEST_CAMERA_CODE);
        } else {
            PhotoPreviewIntent intent = new PhotoPreviewIntent(MultipleChoiceActivity.this);
            intent.setCurrentItem(clickPosition);
            intent.setPhotoPaths(imagePaths);
            startActivityForResult(intent, REQUEST_PREVIEW_CODE);
        }
    }

    /**
     * 调用图片选择器----------------------------------------------------
     */

    /**
     * 回调函数
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    Log.d("list", "list: " + "list = [" + list.size());
                    loadAdpater(list);
                    compressImageList.clear();
                    compressImageList.addAll(list);  //选中的图片添加到compressImageList，等待后续的上传
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    listExtra = data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);
                    ArrayList<String> delete_path = data.getStringArrayListExtra(PhotoPreviewActivity.DELETE_PATH);
                    loadAdpater(listExtra);
                    compressImageList.removeAll(delete_path);  //预览删除的图片从compressImageList中剔除
                    break;
            }
        }

    }

    /**
     * 将选中的图片添加到GridView里面展示
     * @param paths
     */
    private void loadAdpater(ArrayList<String> paths) {
        if (imagePaths != null && imagePaths.size() > 0) {
            imagePaths.clear();
        }
        if (paths.contains("000000")) {
            paths.remove("000000");
        }
        paths.add("000000");
        imagePaths.addAll(paths);
        gridAdapter = new GridAdapter(imagePaths);
        gv_select_house_picture.setAdapter(gridAdapter);
    }

    @Override
    public void onClick(View v) {

    }
    /**
     * item点击事件
     * @param parent
     * @param view
     * @param position
     * @param id
     */

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        imgs = (String) parent.getItemAtPosition(position);
        clickPosition = position;
        requestReadStorageRuntimePermission();
    }
    /**
     * 图片GridView适配器
     */
    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;
        private LayoutInflater inflater;
        public GridAdapter(ArrayList<String> listUrls) {

            this.listUrls = listUrls;
            if (listUrls.size() == 5) {
                listUrls.remove(listUrls.size() - 1);
            }
            inflater = LayoutInflater.from(MultipleChoiceActivity.this);
        }

        public int getCount() {
            return listUrls.size();
        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.i_item_select_image, parent, false);
                holder.image = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final String path = listUrls.get(position);
            if (path.equals("000000")) {
                holder.image.setImageResource(R.mipmap.ic_launcher);
            } else {
                Glide.with(MultipleChoiceActivity.this)
                        .load(path)
                        .error(R.mipmap.ic_launcher)
                        .centerCrop()
                        .crossFade()
                        .into(holder.image);
            }
            return convertView;
        }

        class ViewHolder {
            ImageView image;
        }
    }

    /**
     * 检查网络状态
     * 添加按钮的图片无需上传，需移除
     */
    private void releaseHouseSource() {

        if (NetUtils.isConnected(MultipleChoiceActivity.this)) {
            selectImageFileMap.clear();
            if (compressImageList.size() > 0) {
                if (compressImageList.contains("000000")) {
                    compressImageList.remove("000000");
                }
                new ImageCompressTask().execute();
            } else {
               /* releaseHouseSourceData();*/
            }
        } else {
            ToastUtils.show(MultipleChoiceActivity.this, "当前网络未连接", 1);
        }
    }

    /**
     * 图片压缩
     */
    private class ImageCompressTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Void doInBackground(Void... params) {

            for (int i = 0; i < compressImageList.size(); i++) {
                File oldFile = new File(compressImageList.get(i));
                String newFilePath = compressImageList.get(i);
                Log.e("Ailou", "图片大小" + oldFile.length());
                Log.e("Ailou", "图片大小:" + oldFile.length() / (1024 * 1024) + "兆");
                try {
                    ImageFactory.compressAndGenImage(compressImageList.get(i), newFilePath, 1024, false);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                newFile = new File(newFilePath);
                Log.e("Ailou", "压缩后图片大小" + newFile.length());
                Log.e("Ailou", "压缩后图片大小:" + newFile.length() / (1024 * 1024) + "兆");
                Log.e("Ailou", "newFilePath:" + newFilePath);
                selectImageFileMap.put(compressImageList.get(i), newFile);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            Log.e("imagePathMap", "imagePathMap" + selectImageFileMap.toString());
            pathList.clear();
            totalImageNum = selectImageFileMap.size();
            if (totalImageNum > 0) {
                for (int i = 0; i < imagePaths.size(); i++) {
                    if (selectImageFileMap.containsKey(imagePaths.get(i))) {
                        newFile = selectImageFileMap.get(imagePaths.get(i));
                        uploadFile(newFile);
                    }
                }
            }
        }
    }


    //上传图片文件
    // @param filePath

    private void uploadFile(final File filePath) {
        String url = "http://img.ilou.com.cn/ImageUpload.ashx";
        url = url + "?ImageType=czwj";
       /* RequestParams params = new RequestParams();
        params.addBodyParameter(filePath.getName(), filePath);

        new HttpUtils().send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {


            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                commProgressDialog.dismiss();
                Log.e("MainActivity", "responseInfo.result" + responseInfo.result);
                HouseImage houseImage = JSON.parseObject(responseInfo.result, HouseImage.class);
                if (houseImage.isSuccess()) {
                    if (!"非法操作".equals(houseImage.getMessage())) {
                        pathList.add(houseImage.getFilePath());
                        Log.e("MainActivity!!", "pathList=" + pathList.toString());
                        totalImageNum--;
                        Log.e("MainActivity!!", "totalImageNum=" + totalImageNum);
                        if (totalImageNum == 0) {
                            releaseHouseSourceData();
                        }
                    }
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                commProgressDialog.dismiss();
                Log.e("MainActivity", "上传失败");
                ToastUtils.show(ReleaseRentalHouseActivity.this, "部分图片选择失败!!1", 1);
                totalImageNum--;
                Log.e("MainActivity!!", "totalImageNum=" + totalImageNum);
                if (totalImageNum == 0) {
                    releaseHouseSourceData();
                }
            }
        });*/
    }

}
